<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container{
            width: 600px;
            height: 600px;
            border: 1px solid;
            position: relative;
        }
        .box{
            width: 50px;
            height: 50px;
            background: red;
            position: absolute;
            left: 0px;
            top:0px
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box"></div>
    </div>
<script>
 var boxEle = document.querySelector(".box");
 var dir = "left";
 var speed = 4;
 document.onkeydown = function(e){
    var key = e.key;
    if(key=="ArrowRight"){
        dir = "left"
        speed = Math.abs(speed);
    }else if(key=="ArrowDown"){
        dir = "top";
        speed = Math.abs(speed);
    }else if(key=='ArrowLeft'){
        dir = "left"
        speed = -Math.abs(speed);
    }else if(key=="ArrowUp"){
        dir = "top";
        speed = -Math.abs(speed);
    }
 }

//  来一个绿色食物 ，红色碰到绿色之后 绿色食物消失


setInterval(function(){
    var leftNum = parseInt( getComputedStyle(boxEle)[dir]);
    boxEle.style[dir] = leftNum + speed + "px";
}, 50);

// arrowfunction：箭头函数 ；





</script>
</body>
</html>